#define _CRT_SECURE_NO_WARNINGS
#include "Heap.h"

void HeapPrint(HP* hp)
{
	assert(hp);
	for (int i = 0; i < hp->size; i++)
	{
		printf("%d ", hp->a[i]);
	}
	printf("\n");
}

void HeapInit(HP* hp)
{
	assert(hp);
	hp->capacity = hp->size = 0;
	hp->a = NULL;
}

void AdjustUp(HP* hp, int child)
{
	assert(hp);
	int parent = (child - 1) / 2;
	while (child > 0) {
		if (hp->a[child] > hp->a[parent]) {
			Swap(&hp->a[child], &hp->a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else {
			break;
		}
	}
}

void Heap_pushBack(HP* hp, int x)
{
	assert(hp);
	if (hp->capacity == hp->size) {
		int NewCapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		int* tmp = (int*)realloc(hp->a, sizeof(int) * NewCapacity);
		if (tmp == NULL) {
			perror("relloc fail");
			exit(-1);
		}
		hp->a = tmp;
		hp->capacity = NewCapacity;
	}
	hp->a[hp->size] = x;
	hp->size++;

	AdjustUp(hp, hp->size-1);
}

void AdjustDown(HP* hp, int size, int parent)
{
	assert(hp);
	int minChild = parent * 2 + 1;
	while (minChild < size) {
		if(minChild + 1 < size && hp->a[minChild] < hp->a[minChild + 1])
			minChild++;
		if (hp->a[minChild] > hp->a[parent]) {
			Swap(&hp->a[minChild], &hp->a[parent]);
			parent = minChild;
			minChild = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

bool HeapEmpty(HP* hp)
{
	assert(hp);
	return hp->size == 0;
}

void Heap_popBack(HP* hp)
{
	assert(hp);
	assert(!HeapEmpty(hp));
	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	hp->size--;
	AdjustDown(&hp->a, hp->size, 0);
}

void Swap(int* a, int* b)
{
	int* tmp = *a;
	*a = *b;
	*b = tmp;
}

int HeaptopK(HP* hp)
{
	return hp->a[0];
}